//
//  RJDownloadManager.swift
//  SwiftBaseProject
//
//  Created by monkey_rjpan on 2018/7/19.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import UIKit
import Moya


/// 下载文件类别
///
/// - file: 下载文件
enum Download {
    case file(url: String, saveName: String, savePath: String)
}


extension Download: TargetType {
    
    var baseURL: URL {
        return URL.init(string: "http:/")!
    }
    
    var headers: [String : String]? {
        return nil
    }
    
    var path: String {
        switch self {
        case let .file(url: url, saveName: _, savePath: _):
            //因为baseURL必填，可我不知道对应请求地址，所以采取替换方法，外面传入全部链接
            let changeUrl = url.replacingOccurrences(of: "http:/", with: "")
            return changeUrl
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .file(url: _, saveName: _, savePath: _):
            return .get
        }
    }
    
    var sampleData: Data {
        return Data()
    }
    
    var task: Task {
        switch self {
        case let .file(url: url, saveName: name, savePath: localPath):
            
            //先判断是否存在文件夹路径,不存在创建文件夹
            if FileManager().isExecutableFile(atPath: localPath) == false {
                RJFileManager.createFolder(path: localPath)
            }
            
            //从url中截取后缀为文件类型
            let fileType = url.components(separatedBy: ".").last ?? "png"
            let localLocation: URL = URL.init(fileURLWithPath: localPath+"/"+name+"."+fileType)
            let downloadDestination:DownloadDestination = { _, _ in
                //设置下载为覆盖类型，重名直接覆盖原文件
                return (localLocation, .removePreviousFile) }
            return .downloadDestination(downloadDestination)
        }
    }
    
}

class DownloadManager {
    
    /// 成功回调
    typealias DownloadSuccessClosure = () -> Void

    /// 失败回调
    typealias DownloadFailClosure = (_ errorCode: Int,_ errorMsg: String?) -> Void
    
    /// 使用单例
    static let shared = DownloadManager()

    /// 打印请求信息插件
    let loggerPlugin = RequestLoggerPlugin.init()
    
    private init(){}
    
    
    func requestData<T:TargetType>(target:T,successClosure:@escaping DownloadSuccessClosure,progress: ProgressBlock? = .none,failClosure: @escaping DownloadFailClosure) {
        
        let requestProvider = MoyaProvider<T>(requestClosure:requestTimeoutClosure(target: target),plugins:[loggerPlugin])

        let _ = requestProvider.request(target, callbackQueue: DispatchQueue.global(), progress: progress) { (result) in
            switch result{
            case let .success(response):
                if response.statusCode == 200 {
                    successClosure()
                }else{
                    //接口问题，暂未处理
                    failClosure(response.statusCode,"错误了")
                }
            case let .failure(error):
                failClosure(0,error.errorDescription)
            }
        }
    }
    
    /// 设置请求超时闭包
    ///
    /// - Parameter target: 请求target
    /// - Returns: 请求闭包
    private func requestTimeoutClosure<T:TargetType>(target:T) -> MoyaProvider<T>.RequestClosure{
        let requestTimeoutClosure = { (endpoint:Endpoint, done: @escaping MoyaProvider<T>.RequestResultClosure) in
            do{
                var request = try endpoint.urlRequest()
                request.timeoutInterval = 20 //设置请求超时时间
                done(.success(request))
            }catch{
                return
            }
        }
        return requestTimeoutClosure
    }
}

